package com.dxb.uc;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.dxb.uc.controller.DynamicDsController;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.Properties;
import java.util.concurrent.Executor;


@Component
public class NacosService implements InitializingBean {
    ConfigService configService = buildConfigService();


    public NacosService() throws NacosException {
    }

    public ConfigService buildConfigService() throws NacosException {
        String serverAddr = "localhost";
        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        return NacosFactory.createConfigService(properties);
    }

    /**
     * 获取配置
     */
    public String get(String dataId, String group) throws NacosException {
        return configService.getConfig(dataId, group, 5000);
    }

    /**
     * 修改配置
     */
    public boolean add(String dataId, String group, String add) throws NacosException {
        String content = get(dataId, group);
        return configService.publishConfig(dataId, group, content + "-" + add);
    }

    /**
     * 配置监听
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        configService.addListener(DynamicDsController.dataId, DynamicDsController.group, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println(configInfo);
            }
        });
    }
}
